import 'package:flutter/material.dart';
import 'package:home_framework/models/message_entity.dart';
import 'package:home_framework/view_models/message/chat_message_model.dart';
import 'package:home_framework/view_models/message/stream_socket.dart';
import 'package:provider/provider.dart';

class ChatWithUserPage extends StatefulWidget {
  final String toUserId;
  ChatWithUserPage({Key? key, required this.toUserId}) : super(key: key);

  @override
  _ChatWithUserPageState createState() => _ChatWithUserPageState();
}

class _ChatWithUserPageState extends State<ChatWithUserPage> {
  late final StreamSocket<Map<String, dynamic>> streamSocket;
  final chatMessageModel = ChatMessageModel();

  @override
  void initState() {
    super.initState();
    streamSocket = StreamSocket(
        host: '127.0.0.1', port: 3001, recvEvent: 'chat', userId: 'user1');
    streamSocket.connectAndListen();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('即时聊天-${widget.toUserId}'),
      ),
      body: Stack(
        alignment: Alignment.bottomCenter,
        children: [
          MultiProvider(
            providers: [
              StreamProvider<Map<String, dynamic>?>(
                  create: (context) => streamSocket.getResponse,
                  initialData: null),
              ChangeNotifierProvider.value(value: chatMessageModel)
            ],
            child: StreamDemo(),
          ),
          ChangeNotifierProvider.value(
            child: MessageReplyBar(messageSendHandler: (message) {
              Map<String, String> json = {
                'fromUserId': 'user1',
                'toUserId': widget.toUserId,
                'contentType': 'text',
                'content': message
              };
              streamSocket.sendMessage('chat', json);
            }),
            value: chatMessageModel,
          ),
        ],
      ),
    );
  }

  @override
  void dispose() {
    streamSocket.unregsiter();
    streamSocket.close();
    super.dispose();
  }
}

class StreamDemo extends StatelessWidget {
  StreamDemo({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    Map<String, dynamic>? messageJson = context.watch<Map<String, dynamic>?>();
    if (messageJson != null) {
      context.read<ChatMessageModel>().addMessage(messageJson);
    }
    List<MessageEntity> messages = context.read<ChatMessageModel>().messages;
    return ListView.builder(
      itemBuilder: (context, index) {
        MessageEntity message = messages[index];
        double margin = 20;
        double marginLeft = message.fromUserId == 'user1' ? 60 : margin;
        double marginRight = message.fromUserId == 'user1' ? margin : 60;
        return Container(
          margin: EdgeInsets.fromLTRB(marginLeft, margin, marginRight, margin),
          padding: EdgeInsets.all(15),
          alignment: message.fromUserId == 'user1'
              ? Alignment.centerRight
              : Alignment.centerLeft,
          decoration: BoxDecoration(
              color: message.fromUserId == 'user1'
                  ? Colors.green[300]
                  : Colors.blue[400],
              borderRadius: BorderRadius.circular(10)),
          child: Text(
            message.content,
            style: TextStyle(color: Colors.white),
          ),
        );
      },
      itemCount: messages.length,
    );
  }
}

class MessageReplyBar extends StatelessWidget {
  final ValueChanged<String> messageSendHandler;
  const MessageReplyBar({required this.messageSendHandler, Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      color: Colors.blue[400],
      width: MediaQuery.of(context).size.width,
      height: 80,
      padding: EdgeInsets.fromLTRB(
          20, 10, 20, MediaQuery.of(context).viewInsets.bottom > 0 ? 10 : 20),
      child: Row(
        children: [
          Expanded(
            child: TextField(
              onChanged: (value) {
                context.read<ChatMessageModel>().content = value;
              },
              decoration: InputDecoration(
                hintText: '输入消息',
                fillColor: Colors.white,
                filled: true,
                border: InputBorder.none,
              ),
            ),
          ),
          IconButton(
            onPressed: () {
              messageSendHandler(context.read<ChatMessageModel>().content);
            },
            icon: Icon(
              Icons.near_me,
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}
